package com.xxx.meter.ui.meter.switchgear.info;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

import com.xxx.meter.R;
import com.xxx.meter.base.BaseActivity;
import com.xxx.meter.model.data.swt.SwitchUtil;
import com.xxx.meter.model.http.Api;
import com.xxx.meter.model.http.ApiCallback;
import com.xxx.meter.model.http.bean.MachineSwitchBean;
import com.xxx.meter.model.utils.ButtonUtil;
import com.xxx.meter.model.utils.ToastUtil;
import com.xxx.meter.ui.main.view.DatePickerView;
import com.xxx.meter.ui.main.view.TimePicketView;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MeterSwitchgearInfoActivity extends BaseActivity implements TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {

    @BindView(R.id.set_time_openTime)
    TextView mOpenTime;
    @BindView(R.id.set_time_closeTime)
    TextView mCloseTime;
    @BindView(R.id.main_title)
    TextView mTitle;

    private DatePickerDialog mDatePickerDialog;
    private TimePickerDialog mTimePickerDialog;
    private SimpleDateFormat simpleDateFormat;
    private SimpleDateFormat simpleDateFormatDate;

    private String type;
    private String id;

    private long openTime;
    private long closeTime;

    private int tag;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_set_time;
    }

    @SuppressLint("SimpleDateFormat")
    @Override
    protected void initData() {
        Intent intent = getIntent();
        type = intent.getStringExtra("machineType");
        id = intent.getStringExtra("machineId");
        String name = intent.getStringExtra("machineName");
        mTitle.setText(name);

        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpleDateFormatDate = new SimpleDateFormat("yyyy-MM-dd");
        mDatePickerDialog = DatePickerView.showDataPicket(this, this);
        mTimePickerDialog = TimePicketView.showDataPicket(this, this);

        loadDefaultTime();
    }

    @OnClick({R.id.main_return, R.id.set_time_openTime, R.id.set_time_closeTime, R.id.set_time_btn})
    public void OnClick(View view) {
        if (ButtonUtil.isFastClick()) return;
        switch (view.getId()) {
            case R.id.main_return:
                finish();
                break;
            case R.id.set_time_openTime:
                tag = 1;
                mDatePickerDialog.setTitle("设置开机日期");
                String format = simpleDateFormatDate.format(openTime);
                String[] split = format.split("-");
                if (split.length == 3) {
                    mDatePickerDialog.updateDate(
                            Integer.parseInt(split[0]),
                            Integer.parseInt(split[1]) - 1,
                            Integer.parseInt(split[2])
                    );
                }
                mDatePickerDialog.show();
                break;
            case R.id.set_time_closeTime:
                tag = 2;
                mDatePickerDialog.setTitle("设置关机日期");
                String format1 = simpleDateFormatDate.format(closeTime);
                String[] split1 = format1.split("-");
                if (split1.length == 3) {
                    mDatePickerDialog.updateDate(
                            Integer.parseInt(split1[0]),
                            Integer.parseInt(split1[1]) - 1,
                            Integer.parseInt(split1[2])
                    );
                }
                mDatePickerDialog.show();
                break;
            case R.id.set_time_btn:
                if (openTime == 0) {
                    ToastUtil.showToast("开机时间不能为空");
                    return;
                }
                if (closeTime == 0) {
                    ToastUtil.showToast("关机时间不能为空");
                    return;
                }
                submit();
                break;
        }
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        int time = (hourOfDay * 60 + minute) * 60 * 1000;
        switch (tag) {
            case 1:
                openTime += time;
                mOpenTime.setText("开机时间：" + simpleDateFormat.format(openTime));
                break;
            case 2:
                closeTime += time;
                mCloseTime.setText("关机时间：" + simpleDateFormat.format(closeTime));
                break;
        }
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        long time;
        String timeStr;
        try {
            timeStr = year + "-" + (month + 1) + "-" + dayOfMonth;
            time = simpleDateFormatDate.parse(timeStr).getTime();
        } catch (ParseException e) {
            ToastUtil.showToast("时间选择错误");
            return;
        }
        switch (tag) {
            case 1:
                openTime = time;
                mTimePickerDialog.setTitle("设置开机时间");
                break;
            case 2:
                closeTime = time;
                mTimePickerDialog.setTitle("设置关机时间");
                break;
        }
        mTimePickerDialog.show();
    }

    /**
     * @Data 提交本地修改
     */
    private void submit() {
        showLoading();
        new Thread(new Runnable() {
            @Override
            public void run() {
                SwitchUtil.addOrUpdata(type, id, openTime, closeTime);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideLading();
                        ToastUtil.showToast("提交成功");
                        finish();
                    }
                });
            }
        }).start();
    }

    /**
     * 加载初始化时间
     */
    private void loadDefaultTime() {
        Api.getInstance().getMachineSwitch(type, id)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ApiCallback<MachineSwitchBean>(this, true) {

                    @Override
                    public void onSuccess(MachineSwitchBean bean) {
                        String open = bean.getOpen();
                        String close = bean.getClose();
                        openTime = Long.parseLong(open);
                        closeTime = Long.parseLong(close);
                        if (open != null && !open.isEmpty()) {
                            mOpenTime.setText("开机时间：" + simpleDateFormat.format(openTime));
                        }
                        if (close != null && !close.isEmpty()) {
                            mCloseTime.setText("关机时间：" + simpleDateFormat.format(closeTime));
                        }
                    }

                    @Override
                    public void onError(int errorCode, String errorMessage) {
                        ToastUtil.showToast(errorMessage);
                    }
                });
    }
}
